#include "led.h"
#include "key.h"
#include "delay.h"
#include "usart.h"
#include <string.h>
#include <stdio.h>

uint8_t buffer[100]            = {0};
uint8_t size                   = 0;
uint8_t receive_one_frame_flag = 0;

// 定义进入睡眠模式的函数
void enter_stop_mode(void)
{
    // 1. 设置深睡眠模式
    SCB->SCR |= SCB_SCR_SLEEPDEEP;

    // 2. 开启PWR模块时钟
    RCC->APB1ENR |= RCC_APB1ENR_PWREN;

    // 3. 配置PDDS = 0，表示停机模式
    PWR->CR &= ~PWR_CR_PDDS;

    // 4. 设置电压调节器的工作模式：低功耗模式
    PWR->CR |= PWR_CR_LPDS;

    // 5. 使用WFI指令，进入停机模式
    __WFI();
}

int main(void)
{
    // 初始化
    USART_Init();
    Key_Init();

    // 发送单个字符
    USART_SendChar('a');
    USART_SendChar('t');
    USART_SendChar('\n');

    // 发送字符串
    uint8_t *str = "program start!\n";
    USART_SendString(str, strlen((char *)str));

    while(1)
    {
        str = "would enter stop mode!\n";
        USART_SendString(str, strlen((char *)str));
        Delay_s(2);
        str = "would enter stop mode2!\n";
        USART_SendString(str, strlen((char *)str));
        Delay_ms(10);

        // 允许在停机模式下调试（DBGMCU_CR寄存器）
        //DBGMCU->CR |= DBGMCU_CR_DBG_STOP;  // 置位后，停机模式不关闭调试模块

        // 进入停止模式
        enter_stop_mode();

        // 3. 重新进行系统初始化，设置系统时钟
        SystemInit();

        str = "exit from stop mode!\n";
        USART_SendString(str, strlen((char *)str));

        str = "exit from stop mode2!\n";
        USART_SendString(str, strlen((char *)str));

        str = "exit from stop mode3!\n";
        USART_SendString(str, strlen((char *)str));
    }
}

